#include "qmainctrl.h"
#include "qcomponentinterface.h"
#include <QtGui>
#include <QDir>

QMainCtrl::QMainCtrl(QObject *parent) :
    QObject(parent)
{
}

QMainCtrl::~QMainCtrl()
{
    release();
}

void QMainCtrl::init()
{
    registerComponents();
}

void QMainCtrl::release()
{
    QComponentInterface* pIComponent = NULL;
    foreach (pIComponent, m_componentList)
    {
        if (pIComponent != NULL)
        {
            pIComponent->release();
        }
    }
    delete this;
}

void QMainCtrl::executeCommand(const QString &strCommandId)
{
    QComponentInterface* pIComponent;
    foreach (pIComponent, m_componentList)
    {
        if (pIComponent != NULL)
        {
            pIComponent->onCommand(strCommandId);
        }
    }
}

void QMainCtrl::registerComponents()
{
    QDir pluginsDir(qApp->applicationDirPath());
    pluginsDir.cd("../plugins");
    qDebug() << "dir:" <<  pluginsDir.absolutePath();
    foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = pluginLoader.instance();
        if (plugin) {
            QComponentInterface* pIComponent = qobject_cast<QComponentInterface *>(plugin);
            if (pIComponent)
            {
                registerComponent(pIComponent);
            }
            else
            {
                qDebug() << "Error : Could not load the plugin\"" << fileName << "\"";
            }
        }
    }
}

void QMainCtrl::registerComponent(QComponentInterface *pIComponent)
{
    if (pIComponent != NULL)
    {
        m_componentList.append(pIComponent);
    }
}
